package com.wanmait.server.util;

import com.wanmait.common.exception.CommonException;
import com.wanmait.model.entity.Staff;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

/**
 * @ClassName ShiroUtil
 * @Author 羽
 * @Date 2020/12/11 10:47
 * @Version 1.0
 * Shiro工具类
 **/
public class ShiroUtil {
    //加密算法
    public final static String hashAlgorithmName = "SHA-256";

    //循环次数
    public final static int hashIterations = 16;
    //加密
    public static String sha256(String password, String salt) {
        return new SimpleHash(hashAlgorithmName, password, salt, hashIterations).toString();
    }
    //获取Shiro Session
    public static Session getSession() {
        return SecurityUtils.getSubject().getSession();
    }

    //获取Shiro Subject
    public static Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    //获取Shiro中的真正主体
    public static Staff getUserEntity() {
        return (Staff) SecurityUtils.getSubject().getPrincipal();
    }

    public static Integer getId() {
        return getUserEntity().getId();
    }

    public static void setSessionAttribute(Object key, Object value) {
        getSession().setAttribute(key, value);
    }

    public static Object getSessionAttribute(Object key) {
        return getSession().getAttribute(key);
    }

    public static boolean isLogin() {
        return SecurityUtils.getSubject().getPrincipal() != null;
    }

    public static void logout() {
        SecurityUtils.getSubject().logout();
    }
    /**
    * TODO
    * @author 羽
    * @date 2020/12/11 13:00
    *获取验证码
    **/
    public static String getKaptcha(String key){
        Object kaptcha=getSessionAttribute(key);
        if (kaptcha==null){
            throw new CommonException("验证码已失效!");
        }
        String newCode=kaptcha.toString();
        getSession().removeAttribute(key);
        System.out.println("新的验证码："+newCode);

        return newCode;
    }


//	public static void main(String[] args) {
//		String password="123456";
//		System.out.println(ShiroUtil.sha256(password, ""));
//	}




}
